"""



"""
import random

from datetime import datetime
from flask import current_app,session
from flask import json, jsonify
from flask import make_response
from flask import request

from info import redis_store, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue


# 退出登陆
# 请求路径: /passport/logout
# 请求方式: POST
# 请求参数: 无
# 返回值: errno, errmsg
@passport_blue.route('/logout', methods=['POST'])
def logout():

    #1,清除session信息
    # session.clear()
    session.pop("user_id",None)
    session.pop("nick_name",None)

    #2,返回状态
    return jsonify(errno=RET.OK,errmsg="退出成功")







@passport_blue.route("/login",methods=['POST'])##实际的接口是/passport/login，因为前面加了url_prefix="/passport"
def login():
    # # 1获取参数
    # dict_data = request.json()
    # # 2校验参数
    # moblie = dict_data["moblie"]
    # password = dict_data["password"]
    # 1获取参数
    mobile = request.json.get('mobile')
    password = request.json.get('password')
    #2.1校验该手机用户是否存在
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg='手机用户不存在')
    #2.2校验密码是否正确
    # try:
    #     user.check_passowrd(password)
    # except Exception as e:
    #     current_app.logger.error(e)
    # jsonify(errno=RET.DATAERR, errmsg='密码错误')
    if not user.check_passowrd(password):
        jsonify(errno=RET.DATAERR, errmsg='密码错误')

    # 3设置session
    session['user_id'] = user.id
    session['user_nick_name'] = user.nick_name


    # 3,1记录最后登陆时间
    try:
        user.last_login = datetime.now()
        # db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
    # 4返回状态
    return jsonify(errno = RET.OK,errmsg='登陆成功')


@passport_blue.route("/register",methods=['POST'])##实际的接口是/passport/register，因为前面加了url_prefix="/passport"
def register():
    # json_data = request.data
    # dict_data = json.loads(json_data)
    #获取参数
    dict_data = request.json
    mobile = dict_data.get('mobile')
    sms_code = dict_data.get('sms_code')
    password = dict_data.get('password')

    #校验参数
    #判断用户是否存在
    count = User.query.filter(User.mobile == mobile).count()
    if count >0:
        return jsonify(errno = RET.DATAERR,errmsg='用户已存在')

    #判断短信验证码是否存在
    redis_sms_code = redis_store.get("sms_code:%s"%mobile)
    if not redis_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg='短信验证码不能为空')
    if redis_sms_code != sms_code:
        return jsonify(errno=RET.DATAERR, errmsg='短信验证码填写错误')

    #创建用户，数据入库
    try:
        user = User()
        user.nick_name = mobile
        user.mobile = mobile
        user.password = password


        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='注册失败')

    #返回状态
    return jsonify(errno = RET.OK,errmsg='注册成功')



@passport_blue.route("/sms_code",methods=['POST'])##实际的接口是/passport/sms_code，因为前面加了url_prefix="/passport"
def sms_code():
    json_data = request.data
    dict_data = json.loads(json_data)

    #获取参数
    mobile = dict_data.get('mobile')
    image_code = dict_data.get('image_code')
    image_code_id = dict_data.get('image_code_id')

    #校验参数
    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno = RET.PARAMERR,errmsg='参数不全')

    #判断是否存在图像验证码和图像验证码是否为空
    if not image_code:
        return jsonify(errno = RET.DATAERR,errmsg='图像验证码为空')
    if image_code.lower() != redis_store.get("image_code:%s"%image_code_id).lower():
        return jsonify(errno = RET.DATAERR,errmsg='图像验证码不正确')

    redis_store.delete("image_code:%s"%image_code_id)
    #发送短信验证码
    sms_code = "%06d"%random.randint(0,999999)
    # print("因为现在无法发送短信，所以把验证码打印出来：%s"%sms_code)
    current_app.logger.error("因为现在无法发送短信，所以把验证码打印出来：%s"%sms_code)
    # ccp = CCP()
    #
    # # 注意： 测试的短信模板编号为1
    # #参数1: 给哪个手机号发送
    # #参数2: 发送的内容,['验证码', 时间分钟]
    # #参数3: 表示模板编号, 【云通讯】您使用的是云通讯短信模板，您的验证码是{1}，请于{2}分钟内正确输入
    # result = ccp.send_template_sms('15625070328', [sms_code, 5], 1)
    # if result == -1:
    #     return jsonify(errno = RET.THIRDERR,errmsg='短信发送失败')

    redis_store.set("sms_code:%s"%mobile,sms_code,300)

    #返回结果
    return jsonify(errno = RET.OK,errmsg='发送成功')



@passport_blue.route("/image_code")##实际的接口是/passport/image_code，因为前面加了url_prefix="/passport"
def image_code():

    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")
    if not cur_id:
        return "参数不全"
    if pre_id:
        redis_store.delete("image_code:%s" % pre_id)

    name,text,image_code = captcha.generate_captcha()
    redis_store.set("image_code:%s"%cur_id,text,300)
    response = make_response(image_code)
    response.headers["Content-Type"] = "image/png"
    return response





